<?php

namespace App\Http\Controllers;

use App\Mall;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    public function index(Request $request)
    {
        $name = $request->input('name');
        $email = $request->input('email');

        $map = array();
        if (filled($name)) {
            $map['name'] = $name;
        }
        if (filled($email)) {
            $map['email'] = $email;
        }

        $count = Cache::remember('user_counts', 86400, function () {
            return User::all()->count();
        });
        $users = User::with('address')->where($map)->paginate(10);

        return view('user.index', compact('users', 'count'));
    }

    public function edit($id)
    {
        $malls = Mall::all();
        $user = User::find($id);
        $admin = $user->is_admin;
        if ($admin === '0') {
            $admins = array();
        } else {
            $admins = unserialize($admin);
        }

        return view('user.edit', compact('user', 'malls', 'admins'));
    }

    public function update(Request $request, $id)
    {
        $data = array();
        if (filled($request->input('password'))) {
            $request->validate([
                'password' => 'sometimes|required|string|min:8'
            ]);
            $data['password'] = bcrypt($request->input('password'));
        }

        if (is_null($request->is_admin)) {
            $data['is_admin'] = 0;
        } else {
            $data['is_admin'] = serialize($request->input('is_admin'));
        }

        $user = User::where('id', $id)->update($data);
        if ($user) {
            return redirect(route('admin.user.index'))->with('success', '编辑成功.');
        } else {
            return back()->with('success', '编辑失败！！');
        }
    }
}
